// 缺陷管理API接口
import type { Bug, GetBugsParams, BugStats } from '../types/bug';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { bugData } from '../data/bugData';

// 缺陷API基础路径
const BUG_API_BASE = `${getAPI_BASE_URL_SYNC()}/bugs`;

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 缺陷列表响应格式
interface BugListResponse {
  bugs: Bug[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 缺陷模拟API实现
const mockBugApi = {
  async getBugs(params: GetBugsParams = {}): Promise<ApiResponse<Bug[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, type, project, status, severity, priority, assignee } = params;
    
    // 过滤数据
    let filteredData = [...bugData];
    
    if (search) {
      filteredData = filteredData.filter(bug => 
        bug.title.toLowerCase().includes(search.toLowerCase()) ||
        bug.code.toLowerCase().includes(search.toLowerCase()) ||
        bug.description.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    if (type) {
      filteredData = filteredData.filter(bug => bug.type === type);
    }
    
    if (project) {
      filteredData = filteredData.filter(bug => bug.project === project);
    }
    
    if (status) {
      filteredData = filteredData.filter(bug => bug.status === status);
    }
    
    if (severity) {
      filteredData = filteredData.filter(bug => bug.severity === severity);
    }
    
    if (priority) {
      filteredData = filteredData.filter(bug => bug.priority === priority);
    }
    
    if (assignee) {
      filteredData = filteredData.filter(bug => bug.assignee === assignee);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取缺陷列表成功'
    };
  },

  async createBug(bugData: Partial<Bug>): Promise<ApiResponse<Bug>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newBug: Bug = {
      id: Date.now(),
      code: bugData.code || `BUG-${Date.now().toString().slice(-3)}`,
      title: bugData.title || '',
      description: bugData.description || '',
      type: bugData.type || '功能缺陷',
      severity: bugData.severity || '中',
      priority: bugData.priority || '中',
      status: bugData.status || '新建',
      project: bugData.project || 'KZ-DevOps平台',
      assignee: bugData.assignee || '',
      reporter: bugData.reporter || '',
      environment: bugData.environment || 'Chrome 120.0, Windows 11',
      steps: bugData.steps || '',
      expectedResult: bugData.expectedResult || '',
      actualResult: bugData.actualResult || '',
      attachments: bugData.attachments || [],
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0]
    };
    
    bugData.push(newBug);
    
    return {
      data: newBug,
      total: 1,
      success: true,
      message: '缺陷创建成功'
    };
  },

  async updateBug(bugId: number, bugData: Partial<Bug>): Promise<ApiResponse<Bug>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = bugData.findIndex(bug => bug.id === bugId);
    if (index === -1) {
      throw new Error('缺陷不存在');
    }
    
    bugData[index] = { 
      ...bugData[index], 
      ...bugData, 
      updatedAt: new Date().toISOString().split('T')[0] 
    };
    
    return {
      data: bugData[index],
      total: 1,
      success: true,
      message: '缺陷信息更新成功'
    };
  },

  async deleteBug(bugId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = bugData.findIndex(bug => bug.id === bugId);
    if (index === -1) {
      throw new Error('缺陷不存在');
    }
    
    bugData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '缺陷删除成功'
    };
  },

  async getBugStats(): Promise<ApiResponse<BugStats>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const stats: BugStats = {
      total: bugData.length,
      open: bugData.filter(bug => 
        bug.status === '新建' || bug.status === '已分配' || bug.status === '处理中' || bug.status === '待验证'
      ).length,
      resolved: bugData.filter(bug => bug.status === '已解决' || bug.status === '已关闭').length,
      highSeverity: bugData.filter(bug => bug.severity === '高' || bug.severity === '紧急').length,
      highPriority: bugData.filter(bug => bug.priority === '高' || bug.priority === '紧急').length
    };
    
    return {
      data: stats,
      total: 1,
      success: true,
      message: '获取缺陷统计成功'
    };
  }
};

export const bugApi = {
  // 获取缺陷列表（支持分页、搜索、筛选）
  async getBugs(params: GetBugsParams = {}): Promise<ApiResponse<Bug[]>> {
    if (shouldUseMockServer()) {
      return mockBugApi.getBugs(params);
    }
    try {
      const { page = 1, pageSize = 10, search, type, project, status, severity, priority, assignee } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (type) queryParams.append('type', type);
      if (project) queryParams.append('project', project);
      if (status) queryParams.append('status', status);
      if (severity) queryParams.append('severity', severity);
      if (priority) queryParams.append('priority', priority);
      if (assignee) queryParams.append('assignee', assignee);
      
      const url = `${BUG_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<BugListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 直接返回后端数据，不需要再次解包
        const bugList = backendData.data as BugListResponse;
        return {
          data: bugList.bugs || [],
          total: bugList.total || 0,
          success: true,
          message: backendData.message || '获取缺陷列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取缺陷列表失败');
      }
    } catch (error) {
      console.error('获取缺陷列表失败:', error);
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取缺陷列表失败'
      };
    }
  },

  // 创建缺陷
  async createBug(bugData: Partial<Bug>): Promise<ApiResponse<Bug>> {
    if (shouldUseMockServer()) {
      return mockBugApi.createBug(bugData);
    }
    try {
      const response = await http.post<BackendApiResponse<Bug>>(BUG_API_BASE, bugData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '缺陷创建成功'
        };
      } else {
        throw new Error(backendData.message || '缺陷创建失败');
      }
    } catch (error) {
      console.error('缺陷创建失败:', error);
      return {
        data: {} as Bug,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '缺陷创建失败'
      };
    }
  },

  // 更新缺陷
  async updateBug(bugId: number, bugData: Partial<Bug>): Promise<ApiResponse<Bug>> {
    if (shouldUseMockServer()) {
      return mockBugApi.updateBug(bugId, bugData);
    }
    try {
      const url = `${BUG_API_BASE}/${bugId}`;
      const response = await http.put<BackendApiResponse<Bug>>(url, bugData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '缺陷信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '缺陷信息更新失败');
      }
    } catch (error) {
      console.error('缺陷信息更新失败:', error);
      return {
        data: {} as Bug,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '缺陷信息更新失败'
      };
    }
  },

  // 删除缺陷
  async deleteBug(bugId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockBugApi.deleteBug(bugId);
    }
    try {
      const url = `${BUG_API_BASE}/${bugId}`;
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '缺陷删除成功'
        };
      } else {
        throw new Error(backendData.message || '缺陷删除失败');
      }
    } catch (error) {
      console.error('缺陷删除失败:', error);
      return {
        data: false,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '缺陷删除失败'
      };
    }
  },

  // 获取缺陷统计
  async getBugStats(): Promise<ApiResponse<BugStats>> {
    if (shouldUseMockServer()) {
      return mockBugApi.getBugStats();
    }
    try {
      const url = `${BUG_API_BASE}/stats`;
      const response = await http.get<BackendApiResponse<BugStats>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '获取缺陷统计成功'
        };
      } else {
        throw new Error(backendData.message || '获取缺陷统计失败');
      }
    } catch (error) {
      console.error('获取缺陷统计失败:', error);
      return {
        data: {} as BugStats,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取缺陷统计失败'
      };
    }
  }
};